package com.mamingchao.basic.command;

/**
 * Created by mamingchao on 2020/10/21.
 */
public class Main {
    public static void main(String[] args) {

        Context c = new Context();

        CommandChain cc = new CommandChain();
        cc.add(new InsertCommandA(c))
                .add(new InsertCommandB(c))
                .add(new InsertCommandC(c));

        cc.exec();
        System.out.println(c.msg);

        cc.undo();

        System.out.println(c.msg);
    }

}

class InsertCommandA implements Command{

    public InsertCommandA(Context c) {
        this.c = c;
    }

    Context c;
    String insertStr = "insert A str-- ";
    @Override
    public void exec() {
       c.msg = insertStr + c.msg;
    }

    @Override
    public void undo() {
        c.msg = c.msg.substring(insertStr.length()-1, c.msg.length()-1);
    }
}

class InsertCommandB implements Command{
    Context c;
    String insertStr = "insert B str-- ";

    public InsertCommandB(Context c) {
        this.c = c;
    }

    @Override
    public void exec() {
       c.msg = insertStr + c.msg;
    }

    @Override
    public void undo() {
        c.msg = c.msg.substring(insertStr.length()-1, c.msg.length()-1);
    }
}

class InsertCommandC implements Command{
    Context c;
    String insertStr = "insert C str-- ";

    public InsertCommandC(Context c) {
        this.c = c;
    }

    @Override
    public void exec() {
       c.msg = insertStr + c.msg;
    }

    @Override
    public void undo() {
        c.msg = c.msg.substring(insertStr.length()-1, c.msg.length()-1);
    }
}


